import { Text, StyleSheet, View, TextInput, ActivityIndicator, TouchableOpacity } from 'react-native'
import React, { useState, useRef } from 'react'
import { asyncSetwallet } from "../../redux/features/walletSlice"
import { connect } from 'react-redux'
import { pTx } from '../../utils/dimensions';
import { getNonce, signTransaction, bigNumberFormatUnits, getGasPrice, sendTransaction, getBalance } from 'react-native-web3-wallet';
import { Toast } from '@ant-design/react-native'
import { useRealm, useQuery } from '@realm/react'
import { schemaName } from "../../realm"
import ShadowCard from "../../utils/shadowCard"
import VerifyPasswordModal from "../../components/verifyPasswordModal"
import LinearGradient from 'react-native-linear-gradient';
import NetworkList from "../../utils/NetworkList"


const Transfer = (props) => {
    const realm = useRealm();
    const wallet = useQuery(schemaName.Wallet, wallet => {
        return wallet.filtered('current = true');
    })[0];
    const addModalWalletRefs = useRef()
    const rpcUrl = NetworkList.find(item => item.chainId == wallet.chainId).rpcUrl
    const [toAddress, setToAddress] = useState()
    const [amount, setAmount] = useState()
    const [loading, setLoading] = useState()

    const sendSignTransaction = async (password) => {
        setLoading(true)
        try {
            const gasPrice = await getGasPrice(rpcUrl)
            const nonce = await getNonce(
                rpcUrl,
                wallet.address,
            )
            const sign = await signTransaction(
                wallet.keystore,
                password,
                nonce,
                21000,
                gasPrice,
                toAddress,
                wallet.chainId,
                amount
            )
            addModalWalletRefs.current.setModalVisible(false)
            const res = await sendTransaction(rpcUrl, sign)
            getBalance(rpcUrl, wallet.address).then(res => {
                realm.write(() => {
                    wallet.balance = res.toString()
                });
            })
            props.navigation.goBack()
        } catch (error) {
            Toast.info(error.message)
        }
        setLoading(false)
        addModalWalletRefs.current.setLoading(false)
    }

    const evokePassword = () => {
        if (!toAddress || !amount) return
        if (Number(amount) > bigNumberFormatUnits(wallet.balance)) return Toast.info('余额不足')
        addModalWalletRefs.current.show()
    }

    return (
        <>
            <View style={styles.page}>
                <View style={styles.row}>
                    <Text style={styles.name}>收款地址</Text>
                    <View style={styles.textInputRow}>
                        <TextInput
                            placeholder="输入或粘贴钱包地址"
                            value={toAddress}
                            onChangeText={(value) => setToAddress(value)}
                            style={styles.textareaItem}
                        >
                        </TextInput>
                    </View>
                </View>
                <View style={styles.row}>
                    <Text style={styles.name}>转帐金额</Text>
                    <View style={styles.textInputRow}>
                        <TextInput
                            keyboardType="decimal-pad"
                            placeholder="请输入数量"
                            value={amount}
                            onChangeText={(value) => setAmount(value)}
                            style={styles.textareaItem}
                        />
                        <TouchableOpacity onPress={() => setAmount(bigNumberFormatUnits(wallet.balance).toString())}>
                            <Text style={styles.all}>全部</Text>
                        </TouchableOpacity>
                    </View>
                </View>
                <View style={styles.row}>
                    <Text style={styles.name}>钱包余额</Text>
                    <View style={styles.textInputRow}>
                        <Text style={styles.textareaItem}>
                            {bigNumberFormatUnits(wallet.balance)}
                        </Text>
                    </View>
                </View>
            </View>
            <View style={styles.footerButton}>
                <ShadowCard style={styles.button}>
                    <LinearGradient
                        colors={['rgba(51, 225, 144, 1)', 'rgba(68, 225, 240, 1)']}
                        start={{ x: 0.25, y: 0.25 }}
                        end={{ x: 0.75, y: 0.75 }}
                        style={[styles.linearGradient]}>
                        <TouchableOpacity type="primary" disabled={loading} style={[styles.button]} onPress={() => evokePassword()}>
                            <>
                                {loading ? <ActivityIndicator /> : ""}
                                <Text style={styles.ButtonText}>确认</Text>
                            </>

                        </TouchableOpacity>
                    </LinearGradient>
                </ShadowCard>
            </View>
            <VerifyPasswordModal ref={addModalWalletRefs} sendExamine={sendSignTransaction} />
        </>
    )
}

const mapStateToProps = state => state.wallet

const mapDispatchToProps = {
    asyncSetwallet
}

export default connect(mapStateToProps, mapDispatchToProps)(Transfer)

const styles = StyleSheet.create({
    page: {
        flex: 1,
        paddingHorizontal: pTx(15),
        paddingVertical: pTx(20),
    },
    textInputRow: {
        paddingHorizontal: pTx(15),
        flexDirection: 'row',
        justifyContent: "space-between",
        alignItems: "center",
        backgroundColor: "rgba(247, 247, 247, 1)",
        borderRadius: pTx(6),
    },
    textareaItem: {
        flex: 1,
        borderColor: "rgba(247, 247, 247, 1)",
        borderWidth: 0,
        fontSize: pTx(16),
        paddingVertical: pTx(10),
    },
    name: {
        fontSize: pTx(13),
        paddingTop: pTx(12),
        paddingBottom: pTx(8),
        color: "#0A0C14"
    },
    all: {
        fontSize: pTx(16),
        color: "#06C161"
    },
    footerButton: {
        paddingTop: pTx(15),
        paddingBottom: pTx(63),
        alignItems: "center"
    },
    linearGradient: {
        borderRadius: 6
    },
    button: {
        width: pTx(345),
        height: pTx(55),
        flexDirection: 'row',
        justifyContent: "center",
        alignItems: "center",
    },
    ButtonText: {
        color: "rgba(10, 12, 20, 1)",
        fontSize: pTx(14),
        fontWeight: 'bold'
    }
})